﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
using UnityEngine;
using System;
using Kylin;

public class BundleGenerate {
	readonly static string baseHotUpdatePath = "Assets/Resources/" + ResourcePath.HotFixFolderName;
    static string bundleFolderName = "Bundle";
	static string currentPlatform = "ErrorPlatform";

	[MenuItem("Kylin/AssetBundle/AutoAssignPathToResourcesHotFix", false, 0)]
	public static void AutoAssignPath()
	{
		List<string> fileList = FileUtils.GetAllFileInDir(baseHotUpdatePath);

		ClearAssetBundleName();

		AssignBundleName(fileList);
	}

	public static bool BuildAssetBundlesWin(string revisionFolder)
	{
		string bundleFolder = PrepareBundleFoler(revisionFolder);
		if (string.IsNullOrEmpty(bundleFolder)) return false;

		return (null != BuildPipeline.BuildAssetBundles(bundleFolder, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64));
	}

	public static bool BuildAssetBundlesOSX(string revisionFolder)
	{
		string bundleFolder = PrepareBundleFoler(revisionFolder);
		if (string.IsNullOrEmpty(bundleFolder)) return false;

		return (null != BuildPipeline.BuildAssetBundles(bundleFolder, BuildAssetBundleOptions.None, BuildTarget.StandaloneOSX));
	}

	public static bool BuildAssetBundlesAndroid(string revisionFolder)
    {
		string bundleFolder = PrepareBundleFoler(revisionFolder);
		if (string.IsNullOrEmpty(bundleFolder)) return false;
		
		return (null != BuildPipeline.BuildAssetBundles(bundleFolder, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android));
	}

	public static bool BuildAssetBundlesiOS(string revisionFolder)
    {
		string bundleFolder = PrepareBundleFoler(revisionFolder);
		if (string.IsNullOrEmpty(bundleFolder)) return false;

		return (null != BuildPipeline.BuildAssetBundles(bundleFolder, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.iOS));
	}

	private static string PrepareBundleFoler(string revisionFolder)
    {
		try
        {
			string bundleFolder = revisionFolder + "/" + bundleFolderName;
			Directory.CreateDirectory(bundleFolder);
			return bundleFolder;
		}
		catch(Exception e)
        {
			Debug.LogError("方法 PrepareBundleFoler 发生错误，具体信息：" + e.ToString());
			return null;
        }
	}

	private static void ClearAssetBundleName()
	{
		int length = AssetDatabase.GetAllAssetBundleNames().Length;
		string[] preAssetBundleNames = new string[length];
		for (int i = 0; i < length; ++i)
		{
			preAssetBundleNames[i] = AssetDatabase.GetAllAssetBundleNames()[i];
		}

		for (int j = 0; j < preAssetBundleNames.Length; ++j)
		{
			AssetDatabase.RemoveAssetBundleName(preAssetBundleNames[j], true);
		}

		Debug.Log("<color=#07CEEC>All assetbundle names are cleared</color>");
	}

	private static void AssignBundleName(List<string> fileList)
	{
		foreach (string file in fileList)
		{
			if (!IsFileSuitable(file)) continue;

			string filePath = file;

			filePath = file.Replace("\\", "/");

            if (filePath.Equals(ResourceHelper.bundleConfigPathAddAssets)) continue;

            string fileName = filePath.Replace(baseHotUpdatePath, "");
			fileName = Path.ChangeExtension(fileName, null);
			if (fileName.StartsWith("/")) fileName = fileName.Remove(0, 1);           

            if (fileName.StartsWith("hud/"))
			{
				if (fileName.Contains("@"))
				{
					fileName = fileName.Remove(fileName.LastIndexOf('@'));
				}
			}

            string folderName;
            if (BundleConfig.Instance().ContainsInFolder(fileName, out folderName))
            {
                fileName = folderName;
            }

            fileName = fileName.ToLower();

            AssetImporter.GetAtPath(filePath).assetBundleName = fileName + ".nm";
			AssetDatabase.Refresh();

			//Debug.Log(string.Format("<color=#00b271>Auto assign name for : {0}</color>", file));
		}

		Debug.Log("<color=#07CEEC>All assetbundle names are assigned.</color>");
	}

	private static bool IsFileSuitable(string file)
	{
		string extension = Path.GetExtension(file);

		extension = extension.ToLower();

		if (extension.Equals(".mp3") || extension.Equals(".prefab") || extension.Equals(".fbx") ||
			extension.Equals(".bytes") || extension.Equals(".prefab") || extension.Equals(".png") ||
			extension.Equals(".mat") || extension.Equals(".unity") || extension.Equals(".jpg") ||
			extension.Equals(".jpeg") || extension.Equals(".psd") || extension.Equals(".ttf") ||
			extension.Equals(".txt") || extension.Equals(".bytes") || extension.Equals(".json") ||
			extension.Equals(".csv") || extension.Equals(".asset") || extension.Equals(".controller") ||
			extension.Equals(".overridecontroller") || extension.Equals(".anim") || extension.Equals(".wav") ||
			extension.Equals(".spriteatlas") || extension.Equals(".shader"))
		{
			return true;
		}
		return false;
	}



	public static void SetCurrentPlatform(string platform)
    {
		currentPlatform = platform;
    }
}
